<?php
$REPORTS_DIR = 'reports';		// report files directory
$CHART_HEIGHT = 350;			// total height of the chart image
$CHART_WIDTH_PER_APP = 20;		// width of the bars for each app
$CHART_COL_PADDING = 10;		// space to the right of the bars for each app
$CHART_FOOTER = 50;			// vertical space at the bottom for the X axis, labels, and legend
$CHART_Y_AXIS_WIDTH = 40;		// horizontal padding on the left edge for Y axis and labels
$LABEL_LINE_OFFSET = 4;			// vertical offset between the Y axis labels and light gray horizontal lines

// look at the query string for date and app filters
$valid_dates = array();
$valid_apps = array();
if(strlen(trim($_GET['d'],',')) > 0) {
	$valid_dates = split(',',$_GET['d']);
	// convert string timestamps to ints
	foreach($valid_dates as $i => $d)
		$valid_dates[$i] = intval($d);
}
if(strlen(trim($_GET['a'],',')) > 0)
	$valid_apps = split(',',$_GET['a']);

// if there is only one app, we need more column padding so the dates can be displayed at the bottom
if (count($valid_apps) == 1)
	$CHART_COL_PADDING = 30;
	
// find report text files and read them
$d_entries = scandir($REPORTS_DIR);
$files = array();
foreach($d_entries as $f) {
	$fullname = $REPORTS_DIR . '/' . $f;
	if (is_file($fullname) and strtolower(substr($f,-4)) == '.txt') {
		$d = split('_',$f);
		$d = $d[4];
		$d = strtotime( substr($d,4,2) . '/' . substr($d,6,2) . '/' . substr($d,0,4) );
		if(empty($valid_dates) or in_array($d,$valid_dates))
			$files[$d] = file_get_contents($fullname);
	}
}

// count totals per day for each app
$totals = array();
$all_apps = array();
$num_app_days = 0;
$max_units = 0;
foreach($files as $d => $s) {
	$totals[$d] = array();
	$lines = split("\n", $s);
	unset($lines[0]);
	foreach($lines as $l) {
		$cols = split("\t", $l);
		if( strlen(trim($cols[6])) > 0 and (empty($valid_apps) or in_array($cols[6],$valid_apps)) ) {
			// col6=app col14=country col9=units
			$totals[$d][$cols[6]] += intval($cols[9]);
			if($totals[$d][$cols[6]] > $max_units)
				$max_units = $totals[$d][$cols[6]];
			$all_apps[$cols[6]] = 0;
		}
	}
	$num_app_days += count($totals[$d]);
}

// sort all app names
$all_apps = array_keys($all_apps);
sort($all_apps);
// round max_units to upper 100
if($max_units % 100 > 0) $max_units = $max_units - ($max_units % 100) + 100;

// create image of appropriate width
$img_width = ($CHART_COL_PADDING + $CHART_WIDTH_PER_APP) * $num_app_days  +  $CHART_Y_AXIS_WIDTH;
$img = imagecreatetruecolor($img_width, $CHART_HEIGHT);
// fill with white
$color_white = imagecolorallocate($img, 255, 255, 255);
$color_black = imagecolorallocate($img, 0, 0, 0);
$color_gray = imagecolorallocate($img, 230, 230, 230);
imagefill($img, 0, 0, $color_white);

// draw Y axis
imagefilledrectangle($img, $CHART_Y_AXIS_WIDTH-6, 0, $CHART_Y_AXIS_WIDTH-4, $CHART_HEIGHT-$CHART_FOOTER+4, $color_black);
// draw Y axis markings every 200 units (not pixels, units)
$i = $max_units;
$max_digits = strlen(''.$max_units);
$pixels_per200 = ($CHART_HEIGHT - $CHART_FOOTER) / $max_units;
while($i > 0) {
	$str = (''.$i);
	$digits = strlen($str);
	$curY = $pixels_per200 * ($max_units - $i);
	// draw label for # units
	imagestring($img, 1, 10+($max_digits-$digits)*5, $curY, $str, $color_black);
	$i -= 200;
	// draw horizontal gray line across whole img
	imagefilledrectangle($img, $CHART_Y_AXIS_WIDTH, $curY+$LABEL_LINE_OFFSET, $img_width, $curY+$LABEL_LINE_OFFSET, $color_gray);
}

$curX = $CHART_Y_AXIS_WIDTH;
// only 5 colors are set here
// if there are more than 5 apps in one day, the colors will repeat
$colors = array();
$colors[0] = imagecolorallocate($img, 255, 0, 0);	// red
$colors[1] = imagecolorallocate($img, 0, 255, 0);	// green
$colors[2] = imagecolorallocate($img, 0, 0, 255);	// blue
$colors[3] = imagecolorallocate($img, 0, 255, 255);	// cyan
$colors[4] = imagecolorallocate($img, 255, 0, 255);	// magenta

// go through each day and draw a bar for each app
$avail_height = $CHART_HEIGHT - $CHART_FOOTER;
foreach($files as $d => $s) {
	$startX = $curX;
	$i = 0;
	// loop through every app name that we found
	foreach($all_apps as $app) {
		// if the app exists for this day, draw its totals bar
		if(array_key_exists($app, $totals[$d])) {
			$height = intval( ($totals[$d][$app] / $max_units) * ($avail_height - $LABEL_LINE_OFFSET) );
			imagefilledrectangle($img, $curX, $avail_height - $height, $curX + $CHART_WIDTH_PER_APP, $avail_height, $colors[$i%count($colors)]);
			$curX += $CHART_WIDTH_PER_APP + $CHART_COL_PADDING;
			$i++;
		}
	}
	// draw black line under each day grouping
	imagefilledrectangle($img, $startX, $CHART_HEIGHT-$CHART_FOOTER+2, $curX-$CHART_COL_PADDING, $CHART_HEIGHT-$CHART_FOOTER+4, $color_black);
	// draw the date as a string
	imagestring($img, 2, $startX, $CHART_HEIGHT-$CHART_FOOTER+6, date('M d',$d), $color_black);
}

// draw the legend at the bottom (app names in the appropriate color)
$i = 0;
$curX = $CHART_Y_AXIS_WIDTH;
foreach($all_apps as $app) {
	imagestring($img, 3, $curX, $CHART_HEIGHT-$CHART_FOOTER+30, $app, $colors[$i%count($colors)]);
	$i++;
	$curX += (strlen($app)+5)*5;
}

// output image as a GIF to browser
header('Content-type: image/gif');
imagegif($img);
imagedestroy($img);
?>